package com.xzy.rabbit.demo.workqueue.c;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.xzy.rabbit.common.util.RabbitUtil;
import com.xzy.rabbit.demo.workqueue.Producer;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;

/**
 * 工作模式（Work Queue）
 *
 * @author xzy
 * @date 2021年9月23日
 */
public class Main {
    private static final Integer MESSAGE_COUNT = 10;
    private static final String QUEUE_NAME = "work_queue_c";

    /**
     * 手动应答 + 重新消费
     */
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.创建连接
        ConnectionFactory connectionFactory = RabbitUtil.CONNECTION_FACTORY;
        Connection connection = connectionFactory.newConnection();

        // 2.生产消息（发布任务）
        CountDownLatch countDownLatch = new CountDownLatch(MESSAGE_COUNT);
        Thread produceThread = new Thread(new Producer(connection, QUEUE_NAME, MESSAGE_COUNT, 1L), "PRODUCE");
        produceThread.start();

        // 2.消费消息（工作线程）
        Thread workThread1 = new Thread(new Consumer(connection, QUEUE_NAME, countDownLatch, 1000L, true), "CONSUME1");
        Thread workThread2 = new Thread(new Consumer(connection, QUEUE_NAME, countDownLatch, 100L, false), "CONSUME2");
        workThread1.start();
        workThread2.start();

        countDownLatch.await();
        connection.close();
    }
}
